package com.biqee.framework.interceptor;

import java.util.ArrayList;
import java.util.List;

import com.biqee.framework.context.RequestContext;
import com.biqee.model.db.BqUser;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.ActionProxy;
import com.opensymphony.xwork.interceptor.Interceptor;

/**
 * 用来检查用户是否登录的拦截器
 * 
 * @author guotao.tangt
 *
 */
public class CheckLoginInterceptor implements Interceptor {
	private static final long serialVersionUID = 4970154890658094104L;

	private static List<String> ignoreActionList = new ArrayList<String>();
	
	static {
		// TODO load from config files
		ignoreActionList.add("login");
	}
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void init() {
		
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		boolean isNeedCheck = isNeedCheck(actionInvocation);
		if(isNeedCheck) {
			BqUser user = RequestContext.getUser();
			if (user == null) {
				return Action.LOGIN;
			}
		}

		return actionInvocation.invoke();
	}

	/**
	 * 如果存在用户登录白名单，请在这里添加相关代码
	 * @param actionInvocation
	 * @return
	 */
	private boolean isNeedCheck(ActionInvocation actionInvocation) {
		ActionProxy proxy = actionInvocation.getProxy();
		String actionName = proxy.getActionName().toLowerCase();
		for(String ignoreAction : ignoreActionList) {
			if(ignoreAction.equals(actionName)) {
				return false;
			}
		}
		
		return true;
	}
	
}
